<template>
 <div class="tradPage" >
     <div class="tardtitle">协议签署
         <i class="el-icon-close" @click="$router.push('myTrading')"></i>
     </div>
    <div class="tradcont">
        <div class="tradleft">
           <div class="tradscr">
               <!-- <div class="avatar" :style="{backgroundImage:'url('+imageUrl+')'}" @mousedown='signPic'></div> -->
               <img v-if="imageUrl" :src="imageUrl" class="avatar" :style="{backgroundImage:'url('+imageUrl+')'}" @mousedown='signPic'>
               <el-button type="danger">认证电子签章</el-button>
           </div>
        </div>
        <div class="tradright" id="singbac">
            <div class="pdf-container" style="height:100%">
                
            <el-carousel height="100%"  :autoplay="false" arrow="always" @change="swiperChange" >
                 <el-carousel-item v-for="item in totalPage" :key="item" style="height:100%" :class='"swiper-item"+item' :id='"swiperItem"+item'>
                   <canvas  :id='"the-canvas" + item'></canvas>
                 </el-carousel-item>    
            </el-carousel>
            </div>

        </div>

    </div>  

   <div class="tradfooter">
       <el-button type="danger" @click="makePdf">提交签署</el-button>
       <el-button @click="resdIamge">重置签署</el-button>
   </div>
    
 </div>


</template>
<script>
import * as  pdfjsLib from 'pdfjs-dist'
  import pdfjsWorker from 'pdfjs-dist/build/pdf.worker.entry'
 // import htmlToPdf from '@/utils/htmlpdf';
  import {signPdf,signUpimage,sureUploadimg} from '@/api/userIndex/myTrading';
  import html2canvas from 'html2canvas';
  import axios from 'axios'
  var baseUrl = process.env.VUE_APP_BASE_API;
  var _self;
export default {
     data(){
        return{
            //url:"http://119.97.184.132:8080/profile/upload/2020/08/29/f9374060-a479-4b76-9817-9bfe06d3526b.pdf",
            imageUrl:"http://119.97.184.132:8080/profile/upload/2020/08/29/58f19557-d7dc-4816-92b7-3c35b1d0636d.png",
            totalPage:0,
            scrollTop:0,
            swipePage:1,
            productId:undefined,
            signpdf:[],
            setNum:0,
            setZNum:0,
            uploadUrls:baseUrl+"api/file/imageUpload",
            imageUrls:[]
        }
    },
    created(){
        _self = this;
         pdfjsLib.GlobalWorkerOptions.workerSrc = pdfjsWorker;
         _self.productId=this.$route.query.product;
         
          //this.loadFile(this.url);
        _self.init();   
    },
    methods:{

        init(){
            let data={"productId":_self.productId};
          
          signPdf(data).then((res)=>{
              if(res.code==200){
                 _self.loadFile(res.data);
              }
              
          })
        },
        
    getHtmltoImage(ele,num){ //将HTML转成图片
    //_self.setNum= _self.setNum+1;
    let eleW = ele.offsetWidth;// 获得该容器的宽
    let eleH = ele.offsetHeight;// 获得该容器的高
    let eleOffsetTop = ele.offsetTop;  // 获得该容器到文档顶部的距离
    let eleOffsetLeft = ele.offsetLeft; // 获得该容器到文档最左的距离
    var canvas = document.createElement("canvas");
    var abs = 0;
    let win_in = document.documentElement.clientWidth || document.body.clientWidth; // 获得当前可视窗口的宽度（不包含滚动条）
    let win_out = window.innerWidth; // 获得当前窗口的宽度（包含滚动条）

    if(win_out>win_in){
        abs = (win_out - win_in)/2;    // 获得滚动条宽度的一半
    }
    canvas.width = eleW * 2;    // 将画布宽&&高放大两倍
    canvas.height = eleH * 2;
    var context = canvas.getContext("2d");
    context.scale(2, 2);
    context.translate(-eleOffsetLeft -abs, -eleOffsetTop);
    html2canvas(ele,{
        dpi: 300,
        useCORS:true  //允许canvas画布内 可以跨域请求外部链接图片, 允许跨域请求。
    }).then((canvas)=>{
        //let contractMap={
        //    "key":num,
        //    "value":canvas.toDataURL('image/jpeg', 1.0)
        //}
        //_self.signpdf.push(contractMap);

        _self.signpdf.push(canvas.toDataURL('image/jpeg',1.0));
      
     })
     
    
    },

//转字节流
 dataURItoBlob (base64Data) {
    var byteString;
    if (base64Data.split(',')[0].indexOf('base64') >= 0)
        byteString = atob(base64Data.split(',')[1]);
    else
        byteString = unescape(base64Data.split(',')[1]);
    var mimeString = base64Data.split(',')[0].split(':')[1].split(';')[0];
    var ia = new Uint8Array(byteString.length);
    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }
    return new Blob([ia], {type: mimeString});
},
        
        
        makePdf(){ //提交签章协议
       //_self.$router.push("pay");
       
       //return;
        if (document.querySelectorAll('.mark').length == 0) {
            _self.$message.error("你还没有进行电子签章");
            return;
        }
       
        

          for(var i=0;i<this.totalPage;i++){
                let s = i+1;
               _self.getHtmltoImage(document.querySelector('#swiperItem'+s),s);
          }
          
         // _self.getHtmltoImage(document.querySelector('#swiperItem1'),1);

         if(_self.signpdf.length<=0){
             _self.$message.error("操作过快，请重新提交一次");
             return
         }
         
         _self.signpdf.forEach((ite, index) => {
            // console.log(ite);
            //console.log(index);
            _self.getIamgeUrl(_self.dataURItoBlob(ite),index);

         });
         
         setTimeout(function(){
           console.log(_self.imageUrls);
          _self.getsumBit();
         },1000)

         console.log(_self.imageUrls);
         //_self.getsumBit();
        
    },
    getsumBit(){
    let param = {"productId":_self.productId,"contractMap":_self.imageUrls};
         console.log(param);
         
         signUpimage(param).then((res)=>{
             console.log(res);
             if(res.code==200){
              _self.$message({
               message: '签章提交成功，请等待审核',
              type: 'success'
             });
             _self.signpdf=[];//提交成功后清除掉
             _self.imageUrls=[];
              _self.$router.push({
                name:'pay',
                 query:{
                   contractId:res.data
              }
            })
             ;
             }
         })
    },
    getIamgeUrl(file,index){
     
     
      var formData = new FormData()
       formData.append('file',file);
      axios.post(_self.uploadUrls,
                    formData,
                {headers:{'Content-Type':'multipart/form-data'}}
                ).then((res)=>{
                  console.log(res);
                  let smsb={
                    "key":index,
                    "value":res.data.url
                  }
                  _self.imageUrls.push(smsb);
                })
      
    },
    resdIamge(){
     //重新签章
     var tagElements = document.getElementsByTagName("img");
     for( var m = 0 ; m < tagElements.length ; m++ ){
         if( tagElements[m].className == "sign-img mark" ){
              tagElements[m].parentNode.removeChild( tagElements[m] );
          }
     }
     
    _self.signpdf=[];
      _self.$message({
               message: '重置成功，请重新签章',
              type: 'success'
             });
     _self.init();
        },
        swiperChange(e){
             
             this.swipePage=e+1;
            },
        signPic(e){
          let dom = e.currentTarget.cloneNode(true);
          document.querySelector('#singbac').appendChild(dom);//将拖动的图片放在这个里面
          document.onmousemove = e => { //拖动
          dom.style.left = (this.getPos(e).x - parseInt(dom.clientWidth / 2) - 10) + 'px';
          dom.style.top = (this.getPos(e).y - parseInt(dom.clientHeight / 2) + this.scrollTop - 10) + 'px';
          dom.className="sign-img mark";
          }
           document.onmouseup = e => { //松开
           dom.style.left = this.getPos(e).x - '460'+"px";
           dom.style.top = (this.getPos(e).y + 80 - parseInt(dom.clientHeight / 2) - 105) + 'px';
           document.querySelector('#singbac').removeChild(dom);
           document.querySelector('.swiper-item'+this.swipePage).appendChild(dom);//加入到当面可视区哉
           document.onmousemove = null;
           document.onmouseup = null;
           dom.onmousedown = this.moveTo;
           dom.onclick = this.deleteIt;
          }
        },
        moveTo(e) {
         let odiv = e.currentTarget;
         let disX = e.clientX - odiv.offsetLeft;
         let disY = e.clientY - odiv.offsetTop;
         document.onmousemove = e => {
             if (left <= 0) {
          left = 0;
        } else if (left >= document.querySelector('.swiper-item'+this.swipePage).clientWidth - odiv.clientWidth) {
          left = document.querySelector('.swiper-item'+this.swipePage).clientWidth - odiv.clientWidth;
        } else {
          left = left - 10
        }
 
        if (top <= 0) {
          top = 0;
        } else if (top >= document.querySelector('.swiper-item'+this.swipePage).clientHeight - odiv.clientWidth) {
          top = document.querySelector('.swiper-item'+this.swipePage).clientHeight - odiv.clientWidth;
        } else {
          top = top - 10
        }
        //移动当前元素
        odiv.style.left = left + "px";
        odiv.style.top = top + "px";
         }
         document.onmouseup = e => {
        document.onmousemove = null;
        document.onmouseup = null;
      };
        },
      
    deleteIt(e) {
        
     document.querySelector('.swiper-item'+this.swipePage).removeChild(e.currentTarget);
    },
         
        loadFile (url) {
                 
                  let loadingTask = pdfjsLib.getDocument(url);
                  loadingTask.promise.then((pdf) => {
                   console.log(pdf);
                  let pageNum = pdf.numPages
                  this.totalPage = pageNum;
               for (let i = 1; i <= pageNum; i++) {
            pdf.getPage(i).then((page) => {
             let viewport = page.getViewport({ scale: 0.8, });
          let scaledViewport = page.getViewport({ scale: 0.8, })
          let canvas = document.getElementById('the-canvas' + i)
          let context = canvas.getContext('2d')
          let CSS_UNITS = 96.0 / 72.0
          canvas.height = scaledViewport.height * CSS_UNITS
          canvas.width = scaledViewport.width * CSS_UNITS
          
          let renderContext = {
            transform: [CSS_UNITS,0,0,CSS_UNITS,0,0],
            canvasContext: context,
            viewport: scaledViewport
          }
          let renderTask = page.render(renderContext)
          renderTask.promise.then(() => {
          })
        })
      }
    }, function (reason) {
      console.error(reason)
    })
     
    },
    getPos(ev) {
         return {x: ev.clientX, y: ev.clientY};
        },
    }

}
</script>
<style>
.tradPage{
   position: fixed;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: #f7f7f7;
    z-index: 999;
}
.tradfooter{
    position: fixed;
    height: 80px;
    bottom: 0;
    background: #fff;
    width: 100%;
    text-align: center;
    line-height: 80px;
}
.tradcont{
    position: fixed;
    height: calc(100% - 170px);
    width: 100%;
    top: 70px;
   display: flex;
}
.tardtitle{
  width: 100%;
  position: fixed;
  top: 0;
  height: 50px;
  background: #ffffff;
  line-height: 50px;
  font-size: 20px;
   border-bottom: #dddddd solid 1px;
  text-indent: 20px;
  /* box-shadow: 0 0 4px 2px #f2e8e7; */
}
.tradleft{
    width: 20%;
    float: left;
    height: 100%;
    background: #fff;
    margin-left: 20px;
    text-align: center;
    display: flex;
    justify-content: center;
}
.tradright{
    flex:1;
    margin: 0px 20px;
    background: rgba(0,0,0, 0.2) ;
    text-align: center;
}
.el-carousel {
  height: calc(100% - 20px);
  margin: 10px 0;
}
.tradscr{
    width: 150px;
    height: 150px;
    margin-top: 20px;
}

.sign-img{
  position: absolute;
  z-index: 9999999999999999;
}
.pdf-container{
  position: relative;
}
.el-icon-close{
    line-height: 50px;
    float: right;
    padding-right: 20px;
}
</style>